import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { h, onMounted, reactive, ref } from "vue";
import type { FormItemProps } from "../utils/types";
import { cloneDeep, deviceDetection, isAllEmpty } from "@pureadmin/utils";
import { http } from "@/utils/http";
import { flattenData } from "@/utils/libs";
import { changeHttpLink } from "@/utils/test";

export function useDept() {
  const form = reactive({
    name: "",
    status: null
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const { tagStyle } = usePublicHooks();

  const columns: TableColumnList = [
    {
      label: "部门名称",
      prop: "Name",
      width: 180,
      align: "left"
    },
    {
      label: "排序",
      prop: "Sort",
      minWidth: 70
    },
    {
      label: "状态",
      prop: "Status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.Status)}>
          {row.Status ? "启用" : "停用"}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      minWidth: 200,
      prop: "CreateTime"
    },
    {
      label: "备注",
      prop: "Remark",
      minWidth: 320
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const params = {
      name: form.name,
      status: !isAllEmpty(form.status) ? form.status : -1
    };
    http
      .post(changeHttpLink("/api/System/dept_list"), { data: params })
      .then((res: any) => {
        // 返回格式要求：唯一id加父节点parentId，parentId取父节点id
        if (res.Data != null) {
          const newData = res.Data;
          dataList.value = handleTree(newData, "Id", "ParentId"); // 处理成树结构
        }
        setTimeout(() => {
          loading.value = false;
        }, 300);
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  function formatHigherDeptOptions(treeList, id) {
    // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = treeList[i].Status === 0;
      if (treeList[i].disabled) {
        treeList[i].disabled = treeList[i].id == id;
      }
      formatHigherDeptOptions(treeList[i].children, id);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }

  function openDialog(title = "新增", row: any) {
    const id = row?.Id ?? 0;
    addDialog({
      title: `${title}部门`,
      props: {
        formInline: {
          id,
          higherDeptOptions: formatHigherDeptOptions(
            cloneDeep(dataList.value),
            id
          ),
          parentId: row?.ParentId ?? 0,
          name: row?.Name ?? "",
          principal: row?.Principal ?? "",
          phone: row?.Phone ?? "",
          email: row?.Email ?? "",
          sort: row?.Sort ?? 0,
          status: row?.Status == 1,
          remark: row?.Remark ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了部门名称为【${curData.name}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              Id: 0,
              ParentId: curData?.parentId ?? 0,
              Name: curData?.name ?? "",
              Principal: curData?.principal ?? "",
              Phone: curData?.phone ?? "",
              Email: curData?.email ?? "",
              Sort: parseInt(curData.sort),
              Remark: curData?.remark ?? "",
              Status: curData.status
            };
            if (title !== "新增") {
              formData.Id = curData.id;
            }
            http
              .post(changeHttpLink("/api/System/dept_edit"), {
                data: formData
              })
              .then((res: any) => {
                if (res.Success) {
                  chores();
                } else {
                  message(res.Message, { type: "error" });
                }
                loading.value = false;
              })
              .catch(err => {
                loading.value = false;
                message(err.message, { type: "error" });
              });
          }
        });
      }
    });
  }

  function handleDelete(row) {
    const listChildren = flattenData(row);
    const findIds = listChildren.map(item => {
      return item.Id;
    });
    http
      .post(changeHttpLink("/api/System/dept_remove"), {
        data: {
          listIds: findIds
        }
      })
      .then((res: any) => {
        if (res.Success) {
          message(`您删除了部门名称为【${row.name}】的这条数据`, {
            type: "success"
          });
          onSearch();
        } else {
          message(res.Message, { type: "error" });
        }
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改部门 */
    openDialog,
    /** 删除部门 */
    handleDelete,
    handleSelectionChange
  };
}
